package com.example.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author 王鹤蒲
 * @Date 2023 10 24
 */
@Configuration
@EnableAsync
public class ExecutorConfig {

    @Value("${async.executor.thread.corePoolSize}")
    private int corePoolSize;

    @Value("${async.executor.thread.maximumPoolSize}")
    private int maximumPoolSize;

    @Value("${async.executor.thread.queueCapacity}")
    private int queueCapacity;

    @Value("${async.executor.thread.threadNamePrefix}")
    private String threadNamePrefix;

    @Value("${async.executor.thread.keepAliveSeconds}")
    private int keepAliveSeconds;

    @Bean("asyncExecutor")
    public Executor asyncExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor=new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
        threadPoolTaskExecutor.setMaxPoolSize(maximumPoolSize);
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        threadPoolTaskExecutor.setKeepAliveSeconds(keepAliveSeconds);
        threadPoolTaskExecutor.setThreadNamePrefix(threadNamePrefix);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}
